package com.haorui.lygyd.wxapi.service;

import com.haorui.base.core.enumerate.SearchOperator;
import com.haorui.base.core.exception.BusinessException;
import com.haorui.base.core.model.SearchCondition;
import com.haorui.base.core.utils.BeanUtil;
import com.haorui.base.core.vo.PageableVo;
import com.haorui.base.system.service.SystemConfigService;
import com.haorui.baseutil.utils.HaoRuiDateUtil;
import com.haorui.lygyd.employeemanager.entity.MemberEntity;
import com.haorui.lygyd.employeemanager.repository.MemberRepository;
import com.haorui.lygyd.employeemanager.service.MemberService;
import com.haorui.lygyd.wxapi.dto.WXMemberForgetDto;
import com.haorui.lygyd.wxapi.dto.WXMemberLoginDto;
import com.haorui.lygyd.wxapi.dto.WXMemberRegisDto;
import com.haorui.lygyd.wxapi.dto.WXMemberUpdatePassDto;
import com.haorui.lygyd.wxapi.entity.WXUserInfoEntity;
import com.haorui.lygyd.wxapi.utils.MemberLoginUtil;
import com.haorui.sms.service.SmslogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 郭飞
 * @version 1.0
 * @project jxkf
 * @package com.haorui.jxkf.wxapi.service
 * @createDate 2018/3/20 0020 11:36
 * @modfiyDate
 * @function 数据调动业务层
 */
@Service
@Slf4j
public class WXPublicService {
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private WXUserInfoService weixinUserInfoService;

    @Autowired
    private SmslogService smslogService;


    @Autowired
    private MemberService memberService;

    /***
     *微信接口方法
     *查询单个会员详细信息
     * @return
     */
    public MemberEntity selectMemberDetail() throws BusinessException {
        String memberId = getMemberId();
        MemberEntity memberEntity = memberRepository.findOne(memberId);
        return memberEntity;
    }

    /***
     *微信接口方法
     *会员登录
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MemberEntity login(WXMemberLoginDto dto) throws BusinessException {
        MemberEntity member = memberRepository.findMemberByShouJiHaoMaAndMiMa(dto.getShouJiHaoMa(), dto.getMiMa());
        if (member == null) {
            throw new BusinessException("账号或密码输入错误,请重新输入");
        } else {
            if (member.getShiFouSuoDing()) {
                throw new BusinessException("会员锁定微信不能登录");
            }
            //更新登陆的memberid
            log.info("当前微信登陆用户的openid为：" + dto.getOpenId());
            weixinUserInfoService.wxgetweixinUserByMemberId(dto.getOpenId(), member.getId());
            return member;
        }

    }

    /***
     *微信接口方法
     *会员注册
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MemberEntity zhuCe(WXMemberRegisDto dto) throws BusinessException {
        if (memberRepository.findMemberByShouJiHaoMa(dto.getShouJiHaoMa()) != null) {
            throw new BusinessException("手机号码已注册");
        } else if (memberRepository.findMemberByShengFenZhengHao(dto.getShengFenZhengHao()) != null) {
            throw new BusinessException("身份证号已注册");
        } else {
            dto.setShiFouSuoDing(false);
            MemberEntity dbEnetity = new MemberEntity();
            BeanUtil.beanCopyNotNull(dto, dbEnetity);
            dbEnetity = memberRepository.save(dbEnetity);
            weixinUserInfoService.wxgetweixinUserByMemberId(dto.getOpenId(), dbEnetity.getId());
            return dbEnetity;
        }
    }

    /***
     *微信接口方法
     *忘记密码确认登录
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MemberEntity forgetMiMa(WXMemberForgetDto dto) throws BusinessException {
        MemberEntity memberEntity = memberRepository.findMemberByShouJiHaoMa(dto.getShouJiHaoMa());
        if (memberEntity == null) {
            throw new BusinessException("手机号未注册，请重新注册");
        }
        if (!smslogService.smsCodevalid(dto.getShouJiHaoMa(), dto.getYanZhengMa())) {
            throw new BusinessException("无效的验证码！");
        }
        memberEntity.setMiMa(dto.getMiMa());
        memberRepository.save(memberEntity);
        weixinUserInfoService.wxgetweixinUserByMemberId(dto.getOpenId(), memberEntity.getId());

        return memberEntity;
    }

    /***
     *微信接口方法
     *修改密码确认登录
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MemberEntity updatePass(WXMemberUpdatePassDto dto) throws BusinessException {
        MemberEntity memberEntity = memberService.findOne(dto.getId());
        if (memberEntity == null) {
            throw new BusinessException("手机号未注册，请重新注册");
        }
        if (!memberEntity.getMiMa().equals(dto.getMiMa())) {
            throw new BusinessException("原密码输入不正确");
        }
        memberEntity.setMiMa(dto.getMiMa());
        memberRepository.save(memberEntity);
        weixinUserInfoService.wxgetweixinUserByMemberId(dto.getOpenId(), memberEntity.getId());
        return memberEntity;
    }

    /**
     * 微信接口方法
     * 会员修改密码
     *
     * @param dto
     * @return MemberEntity
     */
    public MemberEntity memberUpdatePass(WXMemberUpdatePassDto dto) throws BusinessException {
        if (memberRepository.findMemberByMiMaAndId(dto.getMiMa(), dto.getId()) == null) {
            throw new BusinessException("旧密码错误");
        }
        MemberEntity dbEnetity = memberRepository.findOne(dto.getId());
        dto.setMiMa(dto.getNewMiMa());
        BeanUtil.beanCopyNotNull(dto, dbEnetity);
        memberRepository.save(dbEnetity);
        return dbEnetity;
    }


    /**
     * 记录公共查询方法
     *
     * @return
     * @throws BusinessException
     */
    public SearchCondition getSearchConditionMember() throws BusinessException {
        String memberId = getMemberId();
        SearchCondition memberIdCon = new SearchCondition();
        memberIdCon.setPro("memberId");
        memberIdCon.setValue(memberId);
        memberIdCon.setOper(SearchOperator.EQ);
        return memberIdCon;
    }

    /**
     * 获取公共参数memberId
     *
     * @return
     * @throws BusinessException
     */
    public String getMemberId() throws BusinessException {
        String memberId = MemberLoginUtil.getMemberId();
        if (memberId == null) {
            throw new BusinessException("会员不存在");
        }
        return memberId;
    }


    /**
     * 根据会员id查询分页
     *
     * @param pageableVo
     * @throws BusinessException
     */
    public void getMemberSearchConditions(PageableVo pageableVo) throws BusinessException {
        String memberId = getMemberId();
        SearchCondition memberIdCondition = new SearchCondition();
        memberIdCondition.setPro("memberId");
        memberIdCondition.setValue(memberId);
        memberIdCondition.setOper(SearchOperator.EQ);
        List<SearchCondition> searchConditionList = new ArrayList<SearchCondition>();
        searchConditionList.addAll(Arrays.asList(pageableVo.getSearchConditions()));
        searchConditionList.add(memberIdCondition);
        pageableVo.setSearchConditions(searchConditionList.toArray(new SearchCondition[searchConditionList.size()]));
    }

    /***
     * 根据推荐人卡号查询推荐人
     * @param memberKaHao
     * @return
     */
    public MemberEntity findMemberByShouJiHaoMa(String memberKaHao) {
        return memberRepository.findMemberByShouJiHaoMa(memberKaHao);
    }

    /**
     * 验证验证码
     *
     * @return
     */
    public boolean checkYanzhengma(String shoujihaoma, String yanzhengma) {
        return smslogService.smsCodevalid(shoujihaoma, yanzhengma);
    }

    /***
     * 验证密码是否正确
     * @param miMa
     * @return
     */
    public boolean checkByMemberMiMaAndId(String miMa) throws BusinessException {
        return memberRepository.findMemberByMiMaAndId(miMa, getMemberId()) != null;
    }

    /**
     * 用户头像和微信号
     *
     * @return
     */
    public WXUserInfoEntity getPhotoWeixin() throws BusinessException {
        List<WXUserInfoEntity> wxUserInfoEntityList = weixinUserInfoService.findUserInfoBymemberId(getMemberId());
        if (wxUserInfoEntityList.size() > 0) {
            return wxUserInfoEntityList.get(0);
        }
        return null;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public long getcurrentDate() {
        return HaoRuiDateUtil.getMillis();
    }
}
